const app = getApp()
Component({
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  properties: {
    count: String, //父子传参
    className: String,
    modelName: String,
    cropper: Boolean
  },
  /**
   * 页面的初始数据
   */
  data: {
    imgs: [],
    count: 1, //限制图片数量
    ishide: false,
    picslist: [],
    imgUrl: app.globalData.imgUrl,
    originImgs: [],
    datalist: [],
    hosts: wx.getStorageSync('uploadUrl'),
    fileName: "",
    cropper: false
  },
  // 上传图片
  methods: {
    chooseImg: function(e) {
      var that = this;
      var imgs = this.data.imgs; 
      var orgimg=this.data.originImgs
      wx.chooseImage({
        count: that.data.count - (that.data.datalist.length || 0),
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function(res) {
          console.log(res,'resresres')
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths;
          var imgs = that.data.imgs;
          var length = imgs.length + orgimg.length + 6 //选择图片长度+原有数据长度，防止key值重复
          console.log(length,'length')

           for (var i = 0; i < tempFilePaths.length; i++) {            
            //判断当前图片大小
            wx.getFileInfo({
              filePath: tempFilePaths[i],
              success(res) {
                console.log("压缩前图片大小:", res.size / 1024, 'kb'); 
              }
            }) 
            
            if (imgs.length > that.data.count - 1) {
              that.setData({
                imgs: imgs
              });
              return false;
            } else {
              var item = {
                imgPath: tempFilePaths[i],
                cropper: true,
                key: length > 0 ? length+i:i  //如果已经有数据追加原有长度为key值
              }
              // 裁剪追加前面
              if (that.data.cropper){
                imgs.unshift(item)
              }else{
                imgs.push(item);
              } 
               
            }
          }
          console.log(imgs,'imgsimgsimgs')
          that.setData({imgs}); 
          if (!that.data.cropper){
            that.uploadFile(imgs);  
          }   
          that.triggerEvent("chooseImg"); //触发回调
        }
      });
    },
    // 删除图片
    deleteImg: function(e) {
      var imgs = this.data.imgs;
      var picslist = this.data.picslist;
      var index = e.currentTarget.dataset.index;
      imgs.splice(index, 1);
      picslist.splice(index, 1);
      this.setData({
        imgs: imgs,
        picslist: picslist
      });
      this.datalist();
      this.triggerEvent("deleteImg"); //触发回调
    },

    // 删除原来图片
    deloriginImg: function(e) {
      var originImgs = this.data.originImgs;
      var index = e.currentTarget.dataset.index;
      originImgs.splice(index, 1);
      this.setData({
        originImgs: originImgs,
      });
      this.datalist();

      this.triggerEvent("deloriginImg"); //触发回调
    },

    // 预览图片
    previewImg: function(e) {
      //获取当前图片的下标
      var index = e.currentTarget.dataset.index;

      //所有图片
      var imgs = this.data.datalist.map(item => {
        return this.data.hosts + item.imgPath
      });
      wx.previewImage({
        //当前显示图片
        current: imgs[index],
        //所有图片
        urls: imgs
      })
    },

    datalist: function() {
      var imglist = []
      if (this.data.picslist.length > 0 && this.data.originImgs.length > 0) {
        var imglist = this.data.originImgs.concat(this.data.picslist)
      } else if (this.data.picslist.length > 0 && this.data.originImgs.length < 1) {
        var imglist = this.data.picslist
      } else {
        var imglist = this.data.originImgs
      }
 

      this.setData({
        datalist: imglist 
      })
      wx.setStorageSync('imgList', imglist)
      if (this.data.datalist.length < Number(this.data.count) - 1) {
        this.setData({
          ishide: false
        });
      }
    },


    //获取裁剪图片
    getCropperImg(e) {
      var that = this;
      var imgs = this.data.imgs
      // imgs.map((item, index) => {
      //   if (index == e.detail.index) {
      //     item.cropper = false
      //   }
      // })

      for (var i =0; i < imgs.length; i++){
        if (i == e.detail.index) {
          imgs[i].cropper = false
        }
      } 
      
      this.setData({ imgs})
      that.cropperUploadFile(e.detail.url, e.detail.index);
    },


    cropperUploadFile: function(pics,idx) {
      var that = this; 
      that.setData({
        // picslist: [],
        loading: true
      })
      wx.uploadFile({
        url: app.globalData.apiUrl + "/" + that.data.modelName + '/protected/comm/file/' + that.data.className + '/fileUpload',
        header: {
          "Authorization": wx.getStorageSync('Authorization'),
        },
        formData: {
          width: 750
        },
        filePath: pics,
        name: 'file',
        success: function(res) {
          if (typeof res.data == "string") {
            var resdata = JSON.parse(res.data)
          }
          if (resdata.success) {
            var resVo = resdata.datas.vo
            var picObj = {
              imgName: resVo.fileName,
              imgPath: resVo.relativeFilePath
            }
            var picdata = that.data.picslist.concat(picObj);
            
            //原图片替换成裁剪图片
            var imgs = that.data.imgs
            imgs.map((item, index) => {
              if (index == idx) {
                item.imgPath = that.data.hosts + resVo.relativeFilePath
              }
            }) 
            // console.log(imgs,'imgs')

            //最后一次更新排序
            var imgArr = imgs 
            if (idx == 0){
              var imgArr = imgs.sort((a, b) => {
                return a.key - b.key
              }) 
              that.triggerEvent("completefun"); //触发回调
            }
           

            that.setData({
              imgs: imgArr,
              picslist: picdata,
              loading: false
            })
            that.datalist();
          }
        },
        fail: function(res) {
          // wx.showToast({
          //   icon: 'none',
          //   title: '图片上传失败',
          // })
        } 
      })
    },




    //上传图片
    uploadFile: function (pics) {
      var that = this;
      that.setData({
        // picslist: [],
        loading:true
      })     
      var flag=false
      for (var i = 0; i < pics.length; i++) { 
         
        (function (i) {
          setTimeout(function () {
            console.log(i);
            wx.uploadFile({
              url: app.globalData.apiUrl + "/" + that.data.modelName + '/protected/comm/file/' + that.data.className + '/fileUpload',
              header: {
                "Authorization": wx.getStorageSync('Authorization'),
              },
              formData: {
                width: 750
              },
              filePath: pics[i].imgPath,
              name: 'file',
              success: function (res) {
                
                if (typeof res.data == "string") {
                  var resdata = JSON.parse(res.data)
                }
                if (resdata.success) {
                  var picObj = {
                    imgName: resdata.datas.vo.fileName,
                    imgPath: resdata.datas.vo.relativeFilePath, 
                  }

                  var picdata = that.data.picslist.concat(picObj);
                  var imgs = that.data.imgs
                  imgs.map((item, index) => {
                    if (index == i) {
                      item.imgPath = that.data.hosts + resdata.datas.vo.relativeFilePath
                    }
                  })

                  that.setData({
                    picslist: picdata
                  })

                  //最后一张关闭遮罩
                  if (i + 1 == pics.length){
                    that.setData({ 
                      loading: false
                    }) 
                  } 
                  that.datalist();
                }
              },
              fail: function (res) {
                // wx.showToast({
                //   icon: 'none',
                //   title: '图片上传失败',
                // })
              }
            })
          }, (i+1)*800); 
        })(i)
       
      }
    },
  },


})